<?php

namespace app\info\controller;

use app\info\model\QuestionModel;
use app\info\model\QuestionnaireItemModel;
use think\admin\Controller;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class Question extends Controller
{
    /**
     * 当前操作数据库
     * @var string
     */
    private string $table = 'Question';

    /**
     * 调查问卷数据管理
     * @auth true
     * @menu true
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function index()
    {
        $this->title = '调查问卷数据管理';
        $query = $this->_query(QuestionModel::class);
        // 加载对应数据
        $this->typeOf = $this->request->get('typeOf', 'index');
        if ($this->typeOf == 'index') $query->where(['is_deleted' => 0]);
        elseif ($this->typeOf == 'is_deleted') $query->where(['is_deleted' => 1]);
        $query->with('Questionnaire')->like('name,tel')->order('id desc')->page(true, true);
    }

    /**
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function detail()
    {
        $id = $this->request->get('id');

        $model = new QuestionModel();

        $detail = $model->where(['id' => $id])->find();

        $data = $detail->toArray();
        $data['content'] = json_decode($detail['content'], true);
        $data['result'] = [];
        $m1 = new QuestionnaireItemModel();
        foreach ($data['content'] as $item) {
            $q = $m1->where(['id' => $item['id']])->find();
            $data['result'][] = [
                'id' => $item['id'],
                'name' => $q->name ?? '',
                'type' => $q->type ?? '',
                'radio' => $q->description ?? '',
                'select' => $item['select']
            ];
        }
        $this->fetch('', ['vo' => $data]);
    }

    /**
     * 表单数据处理
     * @param array $data
     */
    protected function _form_filter(array &$data)
    {

    }

    /**
     * 修改发布状态
     * @auth true
     * @throws DbException
     */
    public function state()
    {
        $this->_applyFormToken();
        $this->_save(QuestionModel::class, $this->_vali([
            'is_deleted.in:0,1' => '状态值范围异常！',
            'is_deleted.require' => '状态值不能为空！',
        ]));
    }


    /**
     * @throws DbException
     */
    public function remove()
    {
        $this->_applyFormToken();
        $this->_save(QuestionModel::class, $this->_vali([
            'is_deleted.in:0,1' => '状态值范围异常！',
            'is_deleted.require' => '状态值不能为空！',
        ]));
    }
}